<template>
  <main-card-admin title="系统日志" :tabs="getTabs()" :loading="loading" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-auth="'sys-log-handle-export'" type="primary" @click="exportLog">导出</a-button>
    </template>
    <template #screen-space>
      <a-row :align="'middle'" justify="space-between">
        <a-col class="mr-24">
          <a-range-picker v-model:value="rangeValue" :show-time="{ format: 'HH:mm' }" format="YYYY-MM-DD HH:mm" @change="onRangeChange" />
        </a-col>
        <a-col flex="1" />
        <a-col>
          <condition-input :condition="condition" @search="onSearch" />
        </a-col>
      </a-row>
    </template>
    <template v-if="isTableRender">
      <GTable
        class="admin-table"
        :columns="tableColumns"
        :data="logList"
        :page-form="pageForm"
        :loading="loading"
        @getDataList="getLogListData"
      />
    </template>
  </main-card-admin>
  <!-- 详情弹窗 -->
  <a-modal
    centered
    title="日志请求参数详情"
    width="988px"
    height="700px"
    :body-style="{ background: '#F2F2F5' }"
    :open="previewState.visibleModal"
    :footer="false"
    :mask-closable="false"
    @cancel="previewCancel"
  >
    <div class="code-and-res">
      <code-editor ref="codeEditorRef" class="code-editor" :style="{ height: `600px)` }" :text-value="codeEditorValue" />
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import dayjs from 'dayjs'
  import { dateFormat } from 'g6-fn'
  import { nextTick, reactive, ref } from 'vue'

  import CodeEditor from '@/components/CodeEditor/index.vue'
  import ConditionInput, { SearchFn } from '@/components/ConditionInput/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import useList from '@/hooks/use-list'
  import { logApi } from '@/services/api'
  import { waitLoading } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'

  import { getTabs } from '../utils'

  interface PageForm {
    username: string
    ip: string
    startTime: string
    endTime: string
    columns: 'operationTime'
    order: 'desc' | 'asc'
  }
  interface PreviewState {
    visibleModal: boolean
    viewData: string
  }
  const condition = [
    { name: 'IP', key: 'ip' },
    { name: '用户名称', key: 'username' }
  ]

  const onSearch = (obj: SearchFn) => {
    console.log('obj:', obj)
    getLogListData({ offset: 1, ...obj })
  }
  // 表格
  const tableColumns = ref([
    {
      title: '用户名称',
      dataIndex: 'username',
      width: 168
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      width: 168
    },
    {
      title: 'IP归属地',
      dataIndex: 'ipHome',
      width: 168
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      width: 168
    },
    {
      title: '浏览器',
      dataIndex: 'browser',
      width: 168
    },
    {
      title: '时间',
      dataIndex: 'operationTime',
      isSort: true,
      width: 168
    },
    {
      title: '操作记录',
      dataIndex: 'operation',
      minWidth: 440
    }
  ])

  const THREE_DAY = 3 * 24 * 60 * 60 * 1000 // 三天的毫秒数
  const rangeValue = ref<any>([dayjs(Date.now() - THREE_DAY), dayjs(Date.now())])

  const {
    pageForm,
    dataList: logList,
    getDataList: getLogListData,
    loading,
    resetPageForm,
    previousPageForm
  } = useList<PageForm, any>(logApi.handleLog, {
    username: '',
    ip: '',
    startTime: dateFormat(rangeValue.value[0], 'YYYY-MM-DD HH:mm:ss'),
    endTime: dateFormat(rangeValue.value[1], 'YYYY-MM-DD HH:mm:ss'),
    columns: 'operationTime',
    order: 'desc'
  })

  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    const order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getLogListData({ offset: 1, order })
  }

  const onRangeChange = (e: any) => {
    let startTime = ''
    let endTime = ''
    if (e) {
      startTime = dateFormat(e[0], 'YYYY-MM-DD HH:mm:ss')
      endTime = dateFormat(e[1], 'YYYY-MM-DD HH:mm:ss')
    }
    getLogListData({ startTime, endTime })
  }

  const isTableRender = ref(true)
  const refreshTable = async () => {
    isTableRender.value = false
    await nextTick()
    isTableRender.value = true
  }

  const reset = () => {
    rangeValue.value = [dayjs(Date.now() - THREE_DAY), dayjs(Date.now())]
    let startTime = dateFormat(rangeValue.value[0], 'YYYY-MM-DD HH:mm:ss')
    let endTime = dateFormat(rangeValue.value[1], 'YYYY-MM-DD HH:mm:ss')
    resetPageForm({ startTime, endTime })
    refreshTable()
  }

  const exportLog = () => {
    waitLoading(
      logApi.exportHandleLog(
        previousPageForm.value,
        {
          isResponseAll: true,
          headers: {
            'Export-Key': 'operation_log_export'
          }
        },
        `操作日志.xlsx`
      )
    )
    console.log(previousPageForm.value, 'previousPageForm')
  }
  /* 查看的逻辑--------------------------------------------------------------------------- */
  const previewState = reactive<PreviewState>({
    visibleModal: false,
    viewData: ''
  })
  const codeEditorValue = ref('') //编辑器当前内容
  const codeEditorRef = ref()
  const loadingShow = ref<boolean>(false)
  const previewData = async (id: string) => {
    // console.log(id)
    loadingShow.value = true
    previewState.visibleModal = true
    // previewState.viewData = await getRequestDetails(id)
    codeEditorValue.value = await getRequestDetails(id)
    codeEditorRef.value.setValue(codeEditorValue.value)
    loadingShow.value = false
  }
  const getRequestDetails = async (id: string): Promise<string> => {
    const { data } = await logApi.requestDetails(
      {},
      {
        urlParams: { id }
      }
    )
    // console.log(data, data)
    return data
  }
  const previewCancel = () => {
    previewState.visibleModal = false
    previewState.viewData = ''
    codeEditorValue.value = ''
    codeEditorRef.value.setValue(codeEditorValue.value)
  }
  /* ----------------------------------------------------------------------------------------------------------- */

  getLogListData()
</script>

<style lang="less" scoped>
  .spin {
    padding: 30px 50px;
    margin: 20px 0;
    margin-bottom: 20px;
    text-align: center;
    background: rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }

  .code-and-res {
    height: 600px;

    .code-editor {
      height: 100%;
    }
  }
</style>
